﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using OnlineEducation.Controllers;
using OnlineEducation.Data;
using System;
using System.Linq;
using System.Threading.Tasks;
using OnlineEducation.Constants;
using OnlineEducation.Models.JQueryTable;
using System.Collections.Generic;
using OnlineEducation.Data.Entities;
using OnlineEducation.Helpers;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.VisualBasic;
using OnlineEducation.Extensions;
using OnlineEducation.Models;
using OnlineEducation.Models.ServerAPIModels;
using OnlineEducation.Helpers.JQueryTable;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using System.Dynamic;
using OnlineEducation.Quartz;
using OnlineEducation.Job;
using Microsoft.Extensions.Configuration;

namespace OnlineEducation.Areas.Controllers
{
    /// <summary>
    /// Course management, you can query, add, edit, delete products
    /// </summary>
    [Area("TeachingPlan")]
    [Route("[controller]/[action]")]
    [Authorize(Roles = "SuperAdmin,Teacher")]
    public class TeachingPlanController : BaseController
    {
        private readonly ILogger _logger;
        private readonly ApplicationDbContext _context;
        private readonly IWebHostEnvironment _env;
        private readonly IJobScheduler _jobScheduler;
        private readonly IConfiguration _configuration;

        public TeachingPlanController(ApplicationDbContext context, ILogger<TeachingPlanController> logger, IWebHostEnvironment env,
            IJobScheduler jobScheduler, IConfiguration configuration)
        {
            _context = context;
            _logger = logger;
            _env = env;
            _jobScheduler = jobScheduler;
            _configuration = configuration;
        }
        /// <summary>
        /// Get all normal plans
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Index()
        {
            var teacherId = User.GetUserID();
            var model = await _context.TeachingPlans
                .Include(n => n.TeachingPlanItems)
                .Include(n => n.Teacher)
                .Include(n => n.Course).ThenInclude(n => n.Lessons)
                .Where(r => r.TeacherId == teacherId && r.Category == 1/*normal plan*/)
                .ToListAsync();

            return View(model);
        }


        /// <summary>
        /// Add a plan.
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Add()
        {

            var teachingPlan = new Data.Entities.TeachingPlan
            {
                IncludeHoliday = true,
                IncludeWeekend = true,
                IncludeWSVacation = true,
                TeachingTimeOption = 1,
                BeginTime = DateTime.Now


            };
            var teacherId = User.GetUserID();

            var courses = await _context.Courses.Where(n => n.TeacherId == teacherId && n.Status == Constants.CourseStatus.Active).ToListAsync();

            ViewBag.Courses = courses.Select(n => FillSubjectName(n));

            ViewBag.WeekdayItems = GetWeekdayListItems();

            return View(teachingPlan);
        }
        /// <summary>
        /// Edit a plan
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id?}")]
        public async Task<IActionResult> Edit(int? id)
        {
            if (!id.HasValue)
            {
                return BadRequest("Id为空");
            }

            var teachingPlan = await _context.TeachingPlans.Where(n => n.Id == id.Value)
                 .Include(n => n.Course)

                 .FirstOrDefaultAsync();

            var teacherId = User.GetUserID();

            var courses = await _context.Courses.Where(n => n.TeacherId == teacherId && n.Status == Constants.CourseStatus.Active).ToListAsync();



            ViewBag.Courses = courses.Select(n => FillSubjectName(n));

            ViewBag.WeekdayItems = GetWeekdayListItems();

            return View(teachingPlan);

        }



        /// <summary>
        /// preview teaching plan detail
        /// </summary>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> Preview(int id)
        {
            var teachingPlan = await _context.TeachingPlans.Where(n => n.Id == id)
                .Include(n => n.TeachingPlanItems)
                .Include(n => n.Teacher)
                .Include(k => k.Course)
                .Include(l => l.Evaluations)
                .Include(k => k.Course)
                .ThenInclude(l => l.Lessons).FirstOrDefaultAsync();

            return View(teachingPlan);
        }
        /// <summary>
        /// Gets the lessons by course identifier.
        /// </summary>
        /// <param name="param">The parameter.</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetLessonsByCourseId(DTParameters param)
        {
            var courseid = param.AdditionalValues.Any() ? param.AdditionalValues.First() : null;

            if (courseid != null)
            {
                int id = int.Parse(courseid);

                var lessons = await _context.Lessons.Where(n => n.Status == 1 && n.CourseId == id).ToListAsync();

                return Json(new DTResult<Lesson>
                {
                    draw = param.Draw,
                    data = lessons,
                    recordsFiltered = lessons.Count,
                    recordsTotal = lessons.Count
                });
            }
            else
            {
                return Json(new DTResult<Lesson>
                {
                    draw = param.Draw,
                    data = new List<Data.Entities.Lesson>(),
                    recordsFiltered = 0,
                    recordsTotal = 0
                });
            }

        }

        /// <summary>
        /// Gets the lessons by course identifier.
        /// </summary>
        /// <param name="param">The parameter.</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetPlanItemsByPlanId(DTParameters param)
        {
            var planid = param.AdditionalValues.Any() ? param.AdditionalValues.First() : null;

            if (planid != null)
            {
                int id = int.Parse(planid);

                var lessons = await _context.TeachingPlanItems.Include(n => n.Lesson)
                    .Where(n => n.TeachingPlanId == id).ToListAsync();

                return Json(new DTResult<TeachingPlanItem>
                {
                    draw = param.Draw,
                    data = lessons,
                    recordsFiltered = lessons.Count,
                    recordsTotal = lessons.Count
                });
            }
            else
            {
                return Json(new DTResult<TeachingPlanItem>
                {
                    draw = param.Draw,
                    data = new List<Data.Entities.TeachingPlanItem>(),
                    recordsFiltered = 0,
                    recordsTotal = 0
                });
            }
        }
        /// <summary>
        /// Save a new or edited plan
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Save([FromBody] OnlineEducation.Data.Entities.TeachingPlan data)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (data.Id == 0)
            {
                try
                {
                    if (!data.CourseId.HasValue || data.CourseId.Value == 0)
                    {
                        return BadRequest("尚未选择课程,请选择需要的课程");
                    }
                    if (data.BeginTime < DateTime.Today)
                    {
                        return BadRequest("计划的开始时间不能小于今天.");
                    }
                    data.TeacherId = User.GetUserID();
                    data.Category = 1;//normal plan
                    data.Status = 0;//unstarted



                    var enddate = data.TeachingPlanItems.OrderByDescending(n => n.BeginTime).Select(n => n.BeginTime).FirstOrDefault();

                    if (enddate != null)
                    {
                        data.EndTime = enddate;
                    }

                    foreach (var item in data.TeachingPlanItems)
                    {
                        item.Status = 0;//unstarted
                        item.MarkAdded();
                    }

                    _context.Add(data);

                    await _context.SaveChangesAsync();

                    foreach (var item in data.TeachingPlanItems)
                    {

                        await _jobScheduler.RunJob<CreateMeetingJob>(item.MeetingNo, item.BeginTime.AddSeconds(5), new Dictionary<string, object>
                       {
                        { "MeetingNo", item.MeetingNo }
                       });
                    }



                    return Json(new { success = true, message = "新增教学计划成功." });

                }
                catch (Exception ex)
                {
                    return Json(new { success = false, message = ex.Message });
                }

            }
            else
            {
                try
                {



                    var teachingPlan = _context.TeachingPlans.Include(n => n.TeachingPlanItems).Where(n => n.Id == data.Id).FirstOrDefault();

                    if ((teachingPlan.BeginTime > DateTime.Now) && (data.BeginTime < DateTime.Today))
                    {
                        return BadRequest("计划的开始时间不能小于今天.");
                    }


                    if (data.BeginTime != default)
                    {
                        teachingPlan.BeginTime = data.BeginTime;
                    }
                    if (data.BeginTime > teachingPlan.BeginTime)
                    {
                        teachingPlan.Status = 0;//set it as unstarted if 
                    }

                    var enddate = data.TeachingPlanItems.OrderByDescending(n => n.BeginTime).Select(n => n.BeginTime).FirstOrDefault();

                    if (enddate != null)
                    {
                        data.EndTime = enddate;
                    }
                    teachingPlan.CourseId = data.CourseId;
                    teachingPlan.IncludeHoliday = data.IncludeHoliday;
                    teachingPlan.IncludeWeekend = data.IncludeWeekend;
                    teachingPlan.IncludeWSVacation = data.IncludeWSVacation;
                    teachingPlan.Name = data.Name;
                    teachingPlan.Notification = data.Notification;
                    teachingPlan.StudentPlanCount = data.StudentPlanCount;

                    teachingPlan.TeachingTimeOption = data.TeachingTimeOption;
                    teachingPlan.TeachingTimeOptionStartTime = data.TeachingTimeOptionStartTime;
                    teachingPlan.TeachingTimeWeekday = data.TeachingTimeWeekday;

                    foreach (var item in teachingPlan.TeachingPlanItems)
                    {
                        var planitem = data.TeachingPlanItems.Where(n => n.LessonId == item.LessonId).FirstOrDefault();

                        if (planitem == null) continue;

                        if (planitem.BeginTime > item.BeginTime)
                        {
                            item.Status = 0;//未开始
                        }

                        item.BeginTime = planitem.BeginTime;

                        item.MarkModified();
                    }


                    _context.Update(teachingPlan);

                    await _context.SaveChangesAsync();


                    foreach (var item in teachingPlan.TeachingPlanItems)
                    {
                        if (item.Status == 2 || item.Status == 1) continue;

                        await _jobScheduler.RunJob<CreateMeetingJob>(item.MeetingNo, item.BeginTime.AddSeconds(5), new Dictionary<string, object>
                       {
                        { "MeetingNo", item.MeetingNo }
                       });
                    }

                    return Json(new { success = true, message = "更新数据成功." });
                }
                catch (Exception ex)
                {
                    return Json(new { success = false, message = ex.Message });
                }

            }
        }

        /// <summary>
        /// Remove a plan
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("{id?}")]
        public async Task<IActionResult> Delete(int? id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            try
            {
                var service = await _context.TeachingPlans.SingleOrDefaultAsync(m => m.Id == id);
                if (service == null)
                {
                    return NotFound();
                }

                _context.TeachingPlans.Remove(service);
                await _context.SaveChangesAsync();

                return Json(new { success = true, message = "删除数据成功." });
            }
            catch (Exception ex)
            {

                return Json(new { success = false, message = ex.Message });
            }


        }

        ///// <summary>
        ///// Changes the status of plan.
        ///// </summary>
        ///// <param name="id">The identifier.</param>
        ///// <returns></returns>
        //[HttpPost("{id}")]
        //public async Task<IActionResult> ChangeStatus(int? id)
        //{
        //    if (!id.HasValue)
        //    {
        //        return BadRequest("id为空");
        //    }

        //    try
        //    {
        //        var code = await _context.TeachingPlans.FindAsync(id.Value);

        //        if (code == null)
        //        {
        //            return NotFound("未找到");
        //        }
        //        if (code.Status == 0)
        //        {
        //            code.Status = 4;
        //        }
        //        else if (code.Status == 4)
        //        {
        //            code.Status = 0;
        //        }


        //        _context.Update(code);

        //        await _context.SaveChangesAsync();

        //        return Json(new { success = true, message = "状态变更成功." });
        //    }
        //    catch (Exception ex)
        //    {

        //        return Json(new { success = false, message = ex.Message });
        //    }


        //}
        /// <summary>
        /// Gets the holidays.
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetHolidays()
        {
            var list = await _context.Holidays.Where(n => n.Status == 1).ToListAsync();

            var hl = new List<HolidayModel>();

            foreach (var item in list)
            {
                hl.Add(new HolidayModel
                {
                    HolidayType = (item.Name == "寒假" || item.Name == "暑假") ? "1" : "2",
                    From = item.FromDate,
                    To = item.ToDate
                });

            }
            return Json(new { success = true, data = hl });
        }

        /// <summary>
        /// Get my plan detail
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetMyTeachingPlan(Period peroid)
        {
            try
            {
                int teacherid = User.GetUserID();

                var myplans = await _context.TeachingPlans.Include(n => n.TeachingPlanItems).ThenInclude(n => n.Lesson)
                    .Where(n => n.TeacherId == teacherid).ToListAsync();

                List<MyEvent> list = new List<MyEvent>();

                foreach (var item in myplans)
                {
                    if (item.Category == 2)
                    {
                        MyEvent e = new MyEvent
                        {
                            Id = item.TeachingPlanItems[0].Id,
                            Title = item.Name,
                            Description = "临时计划",
                            PreviewMaterialURLs = item.MaterialURLs,
                            Start = item.TeachingPlanItems[0].BeginTime,
                            AdhocPlan = true
                        };

                        list.Add(e);
                    }
                    else
                    {
                        foreach (var l in item.TeachingPlanItems)
                        {
                            MyEvent e = new MyEvent
                            {
                                Id = l.Id,
                                Title = l.Lesson.Title,
                                LessonId = l.LessonId,
                                Chapter = l.Lesson.Chapter,
                                Description = l.Lesson.Description,
                                Duration = l.Lesson.Duration.ToString(),
                                PreviewMaterialURLs = l.Lesson.PreviewMaterialURLs,
                                Section = l.Lesson.Section,
                                Start = l.BeginTime,
                                End = l.BeginTime.AddMinutes(l.Lesson.Duration),
                                AdhocPlan = false
                            };

                            list.Add(e);
                        };
                    }
                }

                return Json(new { success = true, data = list });

            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// Get lesson detail
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> GetTeachingPlanItem(int id, bool adhoc)
        {
            if (!adhoc)
            {

                var teachingPlan = await _context.TeachingPlans.Include(n => n.TeachingPlanItems)
                    .ThenInclude(n => n.Lesson).Include(n => n.Teacher).Include(n => n.Course)
                    .Where(n => n.TeachingPlanItems.Any(n => n.Id == id)).FirstOrDefaultAsync();

                if (teachingPlan == null)
                {
                    return PartialView("_Lesson", new LessonModel());
                }

                var teachingPlanItem = teachingPlan.TeachingPlanItems.Where(n => n.Id == id).FirstOrDefault();

                var lessonModel = new LessonModel
                {
                    CourseTitle = teachingPlan.Course.Title,
                    BeginTime = teachingPlanItem.BeginTime,
                    ChapterSection = "第" + teachingPlanItem.Lesson.Chapter + "章 第" + teachingPlanItem.Lesson.Chapter + "节",
                    CurrentLesson = teachingPlanItem.Lesson.Sequence,
                    TotalLessonCount = teachingPlan.TeachingPlanItems.Count,
                    LessonTitle = teachingPlanItem.Lesson.Title,
                    LessonStatus = teachingPlanItem.Status,
                    PreviewMaterialURL = teachingPlanItem.Lesson.PreviewMaterialURLs,
                    TeacherName = teachingPlan.Teacher.FullName,
                    MeetingNo = teachingPlanItem.MeetingNo
                };
                return PartialView("_Lesson", lessonModel);
            }
            else
            {


                var teachingPlanItem = _context.TeachingPlanItems.Where(n => n.Id == id).FirstOrDefault();

                if (teachingPlanItem == null)
                {
                    return PartialView("_adhocLesson", new LessonModel());
                }
                var teachingPlan = await _context.TeachingPlans.Include(n => n.TeachingPlanItems)
                   .Include(n => n.Teacher).Where(n => n.Id == teachingPlanItem.TeachingPlanId).FirstOrDefaultAsync();


                var lessonModel = new LessonModel
                {
                    CourseTitle = teachingPlan.Name,
                    BeginTime = teachingPlanItem.BeginTime,
                    ChapterSection = "临时计划",
                    CurrentLesson = 1,
                    TotalLessonCount = 1,
                    LessonTitle = teachingPlan.Name,
                    LessonStatus = teachingPlanItem.Status,
                    PreviewMaterialURL = teachingPlan.MaterialURLs,
                    TeacherName = teachingPlan.Teacher.FullName,
                    MeetingNo = teachingPlanItem.MeetingNo
                };
                return PartialView("_adhocLesson", lessonModel);
            }


            //var teachingPlan = await _context.TeachingPlans.Include(n => n.TeachingPlanItems)
            //    .ThenInclude(n => n.Lesson).Include(n => n.Teacher).Include(n => n.Course)
            //    .Where(n => n.TeachingPlanItems.Any(n => n.Id == id)).FirstOrDefaultAsync();

            //if (teachingPlan == null)
            //{
            //    return PartialView("_Lesson", new LessonModel());
            //}

            //var teachingPlanItem = teachingPlan.TeachingPlanItems.Where(n => n.Id == id).FirstOrDefault();

            //var lessonModel = new LessonModel
            //{
            //    CourseTitle = teachingPlan.Course.Title,
            //    BeginTime = teachingPlanItem.BeginTime,
            //    ChapterSection = "第" + teachingPlanItem.Lesson.Chapter + "章 第" + teachingPlanItem.Lesson.Chapter + "节",
            //    CurrentLesson = teachingPlanItem.Lesson.Sequence,
            //    TotalLessonCount = teachingPlan.TeachingPlanItems.Count,
            //    LessonTitle = teachingPlanItem.Lesson.Title,
            //    LessonStatus = teachingPlanItem.Status,
            //    PreviewMaterialURL = teachingPlanItem.Lesson.PreviewMaterialURLs,
            //    TeacherName = teachingPlan.Teacher.FullName,
            //    MeetingNo = teachingPlanItem.MeetingNo
            //};

            //return PartialView("_Lesson", lessonModel);




        }

        [HttpPost]
        public async Task<IActionResult> GetMaterialURLs(string meetingno)
        {

            var planitem = await _context.TeachingPlanItems.Include(n => n.Lesson).Where(n => n.MeetingNo == meetingno).FirstOrDefaultAsync();

            if (planitem.Lesson == null)
            {
                var url = _context.TeachingPlans.Where(n => n.Id == planitem.TeachingPlanId).FirstOrDefault()?.MaterialURLs;

                return Json(new { success = !string.IsNullOrEmpty(url), url });
            }
            return Json(new { success = !string.IsNullOrEmpty(planitem.Lesson.MaterialURLs), url = planitem.Lesson.MaterialURLs, id = planitem.Lesson.CourseId });

        }
        [HttpPost]
        public async Task<IActionResult> CheckMeetingStatus(string meetingno)
        {

            var planitem = await _context.TeachingPlanItems.Where(n => n.MeetingNo == meetingno).FirstOrDefaultAsync();


            return Json(new { success = true, status = planitem.Status });

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="meetingno"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult BuildJoinMeetingParams(string meetingno)
        {

            var server_address = _configuration.GetSection("BBB_Server_Address").Value;

            var meeting = new SearchMeetingInfo();

            meeting.meetingID =  meetingno;

            var param = Utility.CreateParams<SearchMeetingInfo>(meeting, ServerAPI.GetMeetingInfo);

            var httprequest = HttpHelper.HttpsGet($"{server_address}/bigbluebutton/api/getMeetingInfo?" + param);

            var response = Utility.XMLToModel<SearchMeetingInfoResponseEntity>(httprequest);

            if (response.returncode == "SUCCESS" )
            {
                var joinmeeting = new JoinMeeting
                {
                    fullName = User.Identity.Name,
                    meetingID = meetingno,
                    password = "111111",
                    userID = User.GetUserID().ToString(),
                    redirect = "true", // true,直接返回了html页面， 为false的时候，返回xml结果，包含会议地址
                    joinViaHtml5 = "true",
                    clientURL = $"{server_address}/",
                    //avatarURL=
                };
                var param1 = Utility.CreateParams<JoinMeeting>(joinmeeting, ServerAPI.Join);

                var joinurl = $"{server_address}/bigbluebutton/api/join?" + param1;

                return Json(new { success = true, url = joinurl });

            }
            else
            {
                _logger.LogError($"Meeting room with No {meetingno} cannot enter in.");

                return Json(new { success = false, message = "教室未创建或已关闭，不能进入，请联系管理员。" });
            }
        }




        /// <summary>
        /// Get all products
        /// </summary>
        /// <returns></returns>
        //[HttpGet]
        public IActionResult AdhocIndex()
        {
            return View();
        }



        /// <summary>
        /// Add an adhoc plan.
        /// </summary>
        /// <returns></returns>
        //[HttpGet]
        public IActionResult AddAdhoc()
        {

            var teachingPlan = new Data.Entities.TeachingPlan
            {
                TeacherId = User.GetUserID(),
                BeginTime = DateTime.Now,
                Status = 0
            };

            ViewBag.Student = _context.ApplicationUsers.Include(n => n.UserRoles)
         .ThenInclude(n => n.Role).Where(n => n.UserRoles.Any(n => n.Role.Name == "Student"))
         .Select(n => new { Id = n.Id, UserName = n.UserName }).ToList();

            return View(teachingPlan);
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetAllAdhocTeachingPlan(DTParameters param)
        {
            var query = _context.TeachingPlans.Include(n => n.Teacher).Where(n => n.Category == 2);

            var newQuery = new SortHelper<TeachingPlan>().Apply(query, param);

            var items = newQuery.Skip(param.Start).Take(param.Length).ToArray();

            var count = newQuery.Count();

            return Json(new DTResult<TeachingPlan>
            {
                draw = param.Draw,
                data = items,
                recordsFiltered = count,
                recordsTotal = count
            });

        }

        /// <summary>
        /// Save a new or edited adhoc plan
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> SaveAdhoc(TeachingPlan data)
        {
            if (string.IsNullOrEmpty(data.Name))
            {
                return BadRequest("计划名称不能为空");
            }
            if (!ModelState.IsValid)
            {

                return BadRequest(ModelState);
            }

            var files = Request.Form.Files;

            if (files != null && files.Any() && files[0] != null && files[0].Length > 0)
            {
                await SaveFiles(data, files);

            }
            //if (data.Id == 0)
            //{
            try
            {
                data.Status = 0;
                data.Category = 2;
                data.TeacherId = User.GetUserID();

                var teachingPlanItem = new TeachingPlanItem
                {
                    BeginTime = data.BeginTime,
                    Status = 0,
                };

                teachingPlanItem.MarkAdded();

                data.TeachingPlanItems = new List<TeachingPlanItem>();

                data.TeachingPlanItems.Add(teachingPlanItem);

                _context.Add(data);

                await _context.SaveChangesAsync();

                await _jobScheduler.RunJob<CreateMeetingJob>(teachingPlanItem.MeetingNo, teachingPlanItem.BeginTime.AddSeconds(5),
                    new Dictionary<string, object>
                    {
                        { "MeetingNo", teachingPlanItem.MeetingNo }
                    }
                );

                if (this.Request.Form["students"].Any())
                {
                    var bookingCount = _context.Bookings.Count() + 1;

                    foreach (var item in this.Request.Form["students"])
                    {
                        Booking booking = new Booking
                        {
                            BookingNo = bookingCount.ToString().PadLeft(5, '0'),
                            StudentId = Convert.ToInt32(item),
                            Discount = 0M,
                            TeachingPlanId = data.Id,
                            TotalAmount = 0M,
                            Status = 0,
                        };

                        _context.Add(booking);
                    }
                    await _context.SaveChangesAsync();
                }

                return Json(new { success = true, message = "新增教学计划成功." });

            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }

            //}
            //else
            //{
            //    try
            //    {
            //        var teachingPlan = _context.TeachingPlans.Include(n => n.TeachingPlanItems).Where(n => n.Id == data.Id).FirstOrDefault();

            //        teachingPlan.BeginTime = data.BeginTime;

            //        //teachingPlan.Name = data.Name;

            //        //teachingPlan.TeacherId = data.TeacherId;

            //        _context.Update(teachingPlan);

            //        await _context.SaveChangesAsync();

            //        return Json(new { success = true, message = "修改教学计划成功." });
            //    }
            //    catch (Exception ex)
            //    {
            //        return Json(new { success = false, message = ex.Message });
            //    }

            //}

            async Task SaveFiles(TeachingPlan data, Microsoft.AspNetCore.Http.IFormFileCollection files)
            {
                var extension = Path.GetExtension(files[0].FileName);

                var filenamewithoutExt = Path.GetFileNameWithoutExtension(files[0].FileName);

                string fileName = filenamewithoutExt + DateTime.Now.ToString("MMddHHmmssfff") + extension;

                using (FileStream fs = System.IO.File.Create(Path.Combine(_env.WebRootPath, "upload", "course", fileName)))//创建文件流
                {
                    await files[0].CopyToAsync(fs);

                    await fs.FlushAsync();
                }

                data.MaterialURLs = "/upload/course/" + fileName;
            }
        }


        /// <summary>
        /// Fills the name of the subject.
        /// </summary>
        /// <param name="course">The course.</param>
        /// <returns></returns>
        private Course FillSubjectName(Course course)
        {
            var codeManager = new CodeManager(_context);
            course.Subject = codeManager.GetValue(course.SubjectCode);
            return course;
        }
        /// <summary>
        /// Gets the weekday list items.
        /// </summary>
        /// <returns></returns>
        private IEnumerable<SelectListItem> GetWeekdayListItems()
        {
            List<SelectListItem> list = new List<SelectListItem>();
            //list.Add(new SelectListItem
            //{
            //    Text = "选择一项",
            //    Value = "0"
            //});
            list.Add(new SelectListItem
            {
                Text = "星期一",
                Value = "1"
            });
            list.Add(new SelectListItem
            {
                Text = "星期二",
                Value = "2"
            });
            list.Add(new SelectListItem
            {
                Text = "星期三",
                Value = "3"
            });
            list.Add(new SelectListItem
            {
                Text = "星期四",
                Value = "4"
            });
            list.Add(new SelectListItem
            {
                Text = "星期五",
                Value = "5"
            });
            list.Add(new SelectListItem
            {
                Text = "星期六",
                Value = "6"
            });
            list.Add(new SelectListItem
            {
                Text = "星期日",
                Value = "7"
            });

            return list;

        }











    }


    public class HolidayModel
    {
        public string HolidayType { get; set; }
        public DateTime From { get; set; }
        public DateTime To { get; set; }

    }
}
